package com.suning.sawp.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.google.common.base.Charsets;
import com.suning.framework.image.service.ImageServiceException;
import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.companymem.AdvanceBaseInfo;
import com.suning.sawp.dto.companymem.CompanyMemBaseInfo;
import com.suning.sawp.dto.companymem.CompanyMemRecordInfo;
import com.suning.sawp.dto.companymem.MdmCityInfoDto;
import com.suning.sawp.dto.companymem.QueryRecordDetailResult;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.intf.companymem.CompanyMemService;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.intf.util.OSSImgService;
import com.suning.sawp.po.util.OSSResult;
import com.suning.sawp.service.impl.companymem.SRSuimgStore;
import com.suning.sawp.service.util.AESUtils;
import com.suning.sawp.service.util.BaseContants;
import com.suning.sawp.service.util.MD5Util;
import com.suning.sawp.web.exception.MobileException;
import com.suning.sawp.web.exception.MyGsonView;

/**
 * 企业会员
 *
 * @author 15050769
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/companyMem")
public class CompanyMemberController extends DjBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CompanyMemberController.class);

    private static String EMAIL_REGEX = "^[\\w-]+[-.\\w]*@[\\w-]+[-.\\w]*\\.[-.\\w]*[\\w-]+$";

    private static String NAME_REGEX = "^[\u4e00-\u9fa5a-zA-Z0-9#_《》()（） ·-]*$";

    private static String ADDRESS_REGEX = "^[\u4e00-\u9fa5a-zA-Z0-9()（）\\.,-]{1,600}$";

    private static String MOBILE_REGEX = "^1\\d{10}$";

    private static String MOBILE2_REGEX = "^(1\\d{10})|(\\d{5,8})$";

    private static String AEARCODE_REGEX = "^\\d{3,4}$";

    private static String IDENTITY_REGEX = "^[0-9a-zA-Z]{6,20}$";

    private static String TAX_REGEX = "^[0-9a-zA-Z]{6,20}$";

    private static String BANK_ACCOUNT_REGEX = "^[0-9\\-]{1,30}$";

    private static String BANK_NAME_REGEX = "^[\u4e00-\u9fa5A-Za-z0-9#\\-()（）]{1,30}$";

    private static String CHECK_EXIST = "0";

    private static String CHECK_NOT_EXIST = "1";

    private static String CHINA_LEVEL = "1";

    private static String CHINA_ZONE = "CN";

    @Autowired
    OSSImgService oSSImgService;

    @Autowired
    StoreManService storeManService;

    @Autowired
    CompanyMemService companyMemService;

    @Autowired
    SRSuimgStore sRSuimgStore;

    /**
     * 校验单位简称存在性
     *
     * @param companyName
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */

    @RequestMapping("/checkCompanyName.do")
    public MyGsonView checkCompanyName(String companyName, Principal principal) throws MobileException {
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        Object[] args = { principal.getName(), companyName };
        LOGGER.info("checkCompanyName staffId:{}, companyName:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验参数合法性
        if (StringUtils.isBlank(companyName) || companyName.length() > 60 || !checkString(NAME_REGEX, companyName)) {
            LOGGER.error("checkCompanyName mobileNum is null for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(returnMsg);
        }
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("checkCompanyName storeManDto is null for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0027);
            return setGsonView(returnMsg);
        }

        ReturnMsg<Boolean> result = companyMemService.checkCompanyNameExists(companyName);

        if (result != null && ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            returnMsg.setData(result.getData() ? CHECK_EXIST : CHECK_NOT_EXIST);
        } else {
            LOGGER.error("checkCompanyName  input result fail  for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
        }
        return setGsonView(returnMsg);
    }

    /**
     * 校验单位简称存在性
     *
     * @param companyName
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/checkEmail.do")
    public MyGsonView checkEmail(String email, Principal principal) throws MobileException {
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        Object[] args = { principal.getName(), email };
        LOGGER.info("checkEmail staffId:{}, email:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验参数合法性
        if (StringUtils.isBlank(email) || !checkString(EMAIL_REGEX, email) || email.length() > 50) {
            LOGGER.error("checkEmail mobileNum is null for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(returnMsg);
        }
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("checkEmail storeManDto is null for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0027);
            return setGsonView(returnMsg);
        }

        ReturnMsg<Boolean> result = companyMemService.checkEmail(email);

        if (result != null && ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            returnMsg.setData(result.getData() ? CHECK_EXIST : CHECK_NOT_EXIST);
        } else {
            LOGGER.error("checkEmail  input result fail  for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
        }
        return setGsonView(returnMsg);
    }

    /**
     * 
     * 根据父级地域信息查询城市信息列表
     *
     * @param zoneId
     * @param zoneLevel
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryCityInfo.do")
    public MyGsonView queryCityInfo(String zoneId, String zoneLevel, Principal principal) throws MobileException {
        ReturnMsg<List<MdmCityInfoDto>> returnMsg = new ReturnMsg<List<MdmCityInfoDto>>();
        Object[] args = { principal.getName(), zoneId, zoneLevel };
        LOGGER.info("queryCityInfo staffId:{}, zoneId:{}， zoneLevel:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验参数合法性
        if (StringUtils.isBlank(zoneId) || !CHINA_ZONE.equals(zoneId) && StringUtils.isBlank(zoneLevel)) {
            LOGGER.error("queryCityInfo input errorl for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(returnMsg);
        }
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("queryCityInfo storeManDto is null for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0027);
            return setGsonView(returnMsg);
        }

        if (CHINA_ZONE.equals(zoneId)) {
            zoneLevel = CHINA_LEVEL;
        }
        ReturnMsg<List<MdmCityInfoDto>> result = companyMemService.queryCityInfo(zoneId, zoneLevel);

        if (result != null && ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            returnMsg.setData(result.getData());
        } else {
            LOGGER.error("queryCityInfo   result fail  for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
        }
        return setGsonView(returnMsg);
    }

    /**
     * 
     * 提交基础信息
     *
     * @param companyMemBaseInfo
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/submitBaseInfo.do")
    public MyGsonView submitBaseInfo(@RequestBody CompanyMemBaseInfo companyMemBaseInfo, Principal principal)
            throws MobileException {
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        Object[] args = { principal.getName(), companyMemBaseInfo };
        LOGGER.info("submitBaseInfo staffId:{}, companyMemBaseInfo:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验参数合法性
        if (!checkSubParm(companyMemBaseInfo, returnMsg)) {
            LOGGER.error("submitBaseInfo mobileNum is null for " + principal.getName());
            return setGsonView(returnMsg);
        }
        ReturnMsg<Boolean> nameCheck = companyMemService.checkCompanyNameExists(companyMemBaseInfo.getCompanyName());
        ReturnMsg<Boolean> emailCheck = companyMemService.checkEmail(companyMemBaseInfo.getEmail());

        if (nameCheck != null && ReturnMsg.SUCCESS.equals(nameCheck.getRetFlag())) {
            if (nameCheck.getData()) {
                returnMsg.setError(ErrorCodeConstants.ERR_0001, "企业会员已经存在，请直接购物吧!");
                return setGsonView(returnMsg);
            }
        } else {
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(returnMsg);
        }

        if (emailCheck != null && ReturnMsg.SUCCESS.equals(emailCheck.getRetFlag())) {
            if (nameCheck.getData()) {
                returnMsg.setError(ErrorCodeConstants.ERR_0001, "邮箱已存在会员，请直接购物或更换邮箱");
                return setGsonView(returnMsg);
            }
        } else {
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(returnMsg);
        }

        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("submitBaseInfo storeManDto is null for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0027);
            return setGsonView(returnMsg);
        }
        ReturnMsg<String> result = companyMemService.submitBaseInfo(companyMemBaseInfo, storeManDto);

        if (result != null && ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            returnMsg.setData(result.getData());
        } else {
            LOGGER.error("submitBaseInfo   result fail  for staffid  " + principal.getName());
            if (result == null) {
                returnMsg.setError(ErrorCodeConstants.ERR_0002);
            } else if (!ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
                returnMsg.setError(result.getErrorCode(), getErrorMessage(result.getErrorMessage()));
            }
        }
        return setGsonView(returnMsg);
    }
    
    private String getErrorMessage(String errorMsg){
        return StringUtils.isBlank(errorMsg)?"系统异常":errorMsg;
    }

    /**
     * 提交身份验证
     *
     * @param businessLicenceId
     * @param businessLicenceUrl
     * @param custNum
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/submitIdentityInfo.do")
    public MyGsonView submitIdentityInfo(String businessLicenceId, String businessLicenceUrl, String custNum,
            Principal principal) throws MobileException {
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        Object[] args = { principal.getName(), businessLicenceId, businessLicenceUrl, custNum };
        LOGGER.info("submitIdentityInfo staffId:{}, businessLicenceId:{}, businessLicenceUrl:{}, custNum:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验参数合法性
        if (!checkString(IDENTITY_REGEX, businessLicenceId) || StringUtils.isBlank(businessLicenceUrl)
                || StringUtils.isBlank(custNum)) {
            LOGGER.error("submitIdentityInfo error is null for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(returnMsg);
        }
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("submitIdentityInfo storeManDto is null for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0027);
            return setGsonView(returnMsg);
        }
        ReturnMsg<String> result = companyMemService.submitIdentityInfo(businessLicenceId, businessLicenceUrl, custNum,
                storeManDto);

        if (result == null) {
            LOGGER.error("submitIdentityInfo  input result fail  for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
        } else if (!ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            returnMsg.setError(result.getErrorCode(), getErrorMessage(result.getErrorMessage()));
        }
        return setGsonView(returnMsg);
    }

    /**
     * 企业会员增票认证
     *
     * @param advanceBaseInfo
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/submitAdvanceInfo.do")
    public MyGsonView submitAdvanceInfo(@RequestBody AdvanceBaseInfo advanceBaseInfo, Principal principal)
            throws MobileException {
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        Object[] args = { principal.getName(), advanceBaseInfo };
        LOGGER.info("submitIdentityInfo staffId:{}, advanceBaseInfo:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验参数合法性
        if (!checkAdvance(advanceBaseInfo, returnMsg)) {
            LOGGER.error("submitAdvanceInfo input is error for " + principal.getName());
            return setGsonView(returnMsg);
        }
        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("submitAdvanceInfo storeManDto is null for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0027);
            return setGsonView(returnMsg);
        }
        ReturnMsg<String> result = companyMemService.submitAdvanceInfo(advanceBaseInfo);

        if (result == null) {
            LOGGER.error("submitAdvanceInfo  input result fail  for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
        } else if (!ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            returnMsg.setError(result.getErrorCode(), getErrorMessage(result.getErrorMessage()));
        }
        return setGsonView(returnMsg);
    }

    /**
     * 查询企业会员记录列表
     *
     * @param queryDate
     * @param queryParm
     * @param index
     * @param size
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryRecordByParm.do")
    public MyGsonView queryRecordByParm(String queryDate, String queryParm, int index, int size, Principal principal)
            throws MobileException {
        ReturnMsg<List<CompanyMemRecordInfo>> returnMsg = new ReturnMsg<List<CompanyMemRecordInfo>>();
        Object[] args = { principal.getName(), queryDate, queryParm };
        LOGGER.info("queryRecordByParm staffId:{}, advanceBaseInfo:{}", args);
        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        // 校验请求入参
        if (StringUtils.isBlank(principal.getName()) || index < 0 || size <= 0
                || size > ConfigConstants.PAGE_SIZE_LIMIT) {
            LOGGER.error("queryRecordByParm input error for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(returnMsg);
        }

        // 校验店员信息
        if (storeManDto == null) {
            LOGGER.error("queryRecordByParm storeManDto is null for " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0027);
            return setGsonView(returnMsg);
        }
        ReturnMsg<List<CompanyMemRecordInfo>> result = companyMemService.queryRecordByParm(queryDate, queryParm, index,
                size, storeManDto);

        if (result != null && ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            returnMsg.setData(result.getData());
        } else {
            LOGGER.error("queryRecordByParm  input result fail  for staffid  " + principal.getName());
            if (result == null) {
                returnMsg.setError(ErrorCodeConstants.ERR_0002);
            } else if (!ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
                returnMsg.setError(result.getErrorCode(), result.getErrorMessage());
            }
        }
        return setGsonView(returnMsg);
    }

    /**
     * 软删除记录
     *
     * @param queryDate
     * @param queryParm
     * @param index
     * @param size
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/deleteRecord.do")
    public MyGsonView deleteRecord(String recordId, Principal principal) throws MobileException {
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        Object[] args = { principal.getName(), recordId };
        LOGGER.info("deleteRecord staffId:{}, recordId:{}", args);
        // 校验请求入参
        if (StringUtils.isBlank(recordId)) {
            LOGGER.error("deleteRecord input error for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(returnMsg);
        }

        // 校验店员信息
        ReturnMsg<String> result = companyMemService.deleteRecord(recordId);

        if (result == null) {
            LOGGER.error("deleteRecord  input result fail  for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
        } else if (!ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            returnMsg.setError(result.getErrorCode(), result.getErrorMessage());
        }

        return setGsonView(returnMsg);
    }

    /**
     * 查询记录详情
     *
     * @param queryDate
     * @param queryParm
     * @param index
     * @param size
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/quertRecordDetail.do")
    public MyGsonView quertRecordDetail(String recordId, String custNum, Principal principal) throws MobileException {
        ReturnMsg<QueryRecordDetailResult> returnMsg = new ReturnMsg<QueryRecordDetailResult>();
        Object[] args = { principal.getName(), recordId };
        LOGGER.info("quertRecordDetail staffId:{}, recordId:{}", args);
        // 校验请求入参
        if (StringUtils.isBlank(recordId) || StringUtils.isBlank(custNum)) {
            LOGGER.error("quertRecordDetail input error for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(returnMsg);
        }

        // 校验店员信息
        ReturnMsg<QueryRecordDetailResult> result = companyMemService.quertRecordDetail(recordId, custNum);

        if (result != null && ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            returnMsg.setData(result.getData());
        } else {
            LOGGER.error("quertRecordDetail  input result fail  for staffid  " + principal.getName());
            if (result == null) {
                returnMsg.setError(ErrorCodeConstants.ERR_0002);
            } else if (!ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
                returnMsg.setError(result.getErrorCode(), result.getErrorMessage());
            }
        }
        return setGsonView(returnMsg);
    }

    /**
     * 提交敏感信息
     *
     * @param mId
     * @param mobileNum
     * @param principal
     * @return
     * @throws MobileException
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/submitSensitiveVisitRecord.do")
    public MyGsonView submitSensitiveVisitRecord(String mId, String mobileNum, Principal principal,
            HttpServletRequest request) throws MobileException {
        ReturnMsg<QueryRecordDetailResult> returnMsg = new ReturnMsg<QueryRecordDetailResult>();
        Object[] args = { principal.getName(), mId, mobileNum };
        LOGGER.info("submitSensitiveVisitRecord staffId:{}, mId:{},mobileNum:{}", args);
        // 校验请求入参
        if (StringUtils.isBlank(mId) || StringUtils.isBlank(mobileNum)) {
            LOGGER.error("submitSensitiveVisitRecord input error for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(returnMsg);
        }

        StoreManDto storeManDto = storeManService.queryStoreManAttachInfo(principal.getName());
        String requestIp = getUserIp(request);
        // 校验店员信息
        ReturnMsg<String> result = companyMemService.submitSensitiveVisitRecord(mId, mobileNum,
                storeManDto.getStaffId(), requestIp);

        if (result == null) {
            LOGGER.error("queryRecordByParm  input result fail  for staffid  " + principal.getName());
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
        } else if (!ReturnMsg.SUCCESS.equals(result.getRetFlag())) {
            returnMsg.setError(result.getErrorCode(), result.getErrorMessage());
        }
        return setGsonView(returnMsg);
    }

    private String getUserIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        boolean forwardFlag = hasDeepIp(ip);
        if (forwardFlag) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        boolean proxClientFlag = hasDeepIp(ip);
        if (proxClientFlag) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        boolean wlProxyClient = hasDeepIp(ip);
        if (wlProxyClient) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        boolean httpClientFlag = hasDeepIp(ip);
        if (httpClientFlag) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        boolean httpXforwardFlag = hasDeepIp(ip);
        if (httpXforwardFlag) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private boolean hasDeepIp(String ip) {
        return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
    }

    /**
     * 上传图片 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param multipartRequest
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/uploadImg.htm")
    @ResponseBody
    public MyGsonView uploadImg(HttpServletRequest request) {
        MyGsonView gsonView = createGsonView();
        MultipartRequest mutilRequest = (MultipartRequest) request;
        MultipartFile imageFile = mutilRequest.getFile("file");
        String type = request.getParameter("type");
        String custNum = request.getParameter("custNum");
        // 图片大小不能超过2M
        if (imageFile.getSize() > 2097152) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0044);
            return gsonView;
        }

        String typeParm = getImgIndex(type);
        String custNumParm = AESUtils.decrypt(custNum, ConfigConstants.AES_KEY);
        // 校验请求入参
        if (StringUtils.isBlank(typeParm) || StringUtils.isBlank(custNum) || StringUtils.isBlank(custNumParm)) {
            LOGGER.error("uploadImg input error for custNum :{},type:{} ", custNum, type);
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
            return gsonView;
        }
        LOGGER.info("uploadImg error for custNum :{},type :{} ", custNumParm, type);
        String fileName = imageFile.getOriginalFilename();
        if (!( StringUtils.isNotBlank(fileName) && (StringUtils
                .lowerCase(fileName).endsWith(".jpeg") || StringUtils.lowerCase(fileName).endsWith(".jpg") || StringUtils
                .lowerCase(fileName).endsWith(".png")))) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        }
        if (null != imageFile && !imageFile.isEmpty() && null != imageFile.getContentType()) {
            MediaType mediaType = MediaType.parseMediaType(imageFile.getContentType());
            List<MediaType> supports = MediaType.parseMediaTypes("image/*");
            for (MediaType support : supports) {
                if (support.includes(mediaType)) {
                    OSSResult oSSResult = null;
                    InputStream in = null;
                    try {
                        in = imageFile.getInputStream();
                        custNumParm = MD5Util.getMD5(custNumParm, Charsets.UTF_8.toString());
                        oSSResult = sRSuimgStore.onlyUpload(custNumParm, typeParm, in);
                        gsonView.addStaticAttribute(BaseContants.DATA, oSSResult);
                    } catch (IOException ex) {
                        LOGGER.error("uimg uploadImg io exception", ex);
                        setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
                    } catch (ImageServiceException e) {
                        LOGGER.error("uimg uploadImg exception", e);
                        setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
                    } finally {
                        IOUtils.closeQuietly(in);
                    }
                    break;
                }
                setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            }
        } else {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
        }
        return gsonView;
    }

    private String getImgIndex(String type) {
        //  0：营业执照；1：税务登记证；2：一般纳税人
        //A11:营业执照副本,B11:税务登记证副本,D11:一般纳税人证书：
        if ("0".equals(type)) {
            return "A11";
        }
        if ("1".equals(type)) {
            return "B11";
        }
        if ("2".equals(type)) {
            return "D11";
        }
        return null;
    }

    /**
     * 增票入参校验
     * 
     * @param advanceBaseInfo
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private boolean checkAdvance(AdvanceBaseInfo advanceBaseInfo, ReturnMsg<String> returnMsg) {

        if (advanceBaseInfo == null || StringUtils.isBlank(advanceBaseInfo.getAreaId())
                || StringUtils.isBlank(advanceBaseInfo.getCityId())
                || StringUtils.isBlank(advanceBaseInfo.getProvinceId())
                || StringUtils.isBlank(advanceBaseInfo.getBankAcount())
                || StringUtils.isBlank(advanceBaseInfo.getBankName())
                || StringUtils.isBlank(advanceBaseInfo.getCustNum())
                || StringUtils.isBlank(advanceBaseInfo.getLicenceName())
                || StringUtils.isBlank(advanceBaseInfo.getRegisterAddress())
                || StringUtils.isBlank(advanceBaseInfo.getRegisterPhoneNum())
                || StringUtils.isBlank(advanceBaseInfo.getTaxId())
                || StringUtils.isBlank(advanceBaseInfo.getTaxManUrl())
                || StringUtils.isBlank(advanceBaseInfo.getTaxUrl())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return false;
        }

        if (!checkString(NAME_REGEX, advanceBaseInfo.getLicenceName())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "开票单位名称不合法");
            return false;
        }
        if (advanceBaseInfo.getLicenceName().length() > 60) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "开票单位名称长度超过60位");
            return false;
        }
        if (!checkString(TAX_REGEX, advanceBaseInfo.getTaxId())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "税务登记号不合法");
            return false;
        }
        if (!checkString(MOBILE2_REGEX, advanceBaseInfo.getRegisterPhoneNum())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "注册联系方式不合法");
            return false;
        }
        if ((StringUtils.isNotBlank(advanceBaseInfo.getAreaCode()) && !checkString(AEARCODE_REGEX,
                advanceBaseInfo.getAreaCode()))) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "区号不合法");
            return false;
        }
        if (!checkString(BANK_NAME_REGEX, advanceBaseInfo.getBankName())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "开户银行名称不合法");
            return false;
        }
        if (!checkString(ADDRESS_REGEX, advanceBaseInfo.getRegisterAddress())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "注册地址不合法");
            return false;
        }
        if (!checkString(BANK_ACCOUNT_REGEX, advanceBaseInfo.getBankAcount())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "银行账号不合法");
            return false;
        }

        if (advanceBaseInfo.getTaxManUrl().length() > 128) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "一般纳税人图片链接超长");
            return false;
        }

        if (advanceBaseInfo.getTaxUrl().length() > 128) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "税务登记证图片链接超长");
            return false;
        }

        return true;

    }

    /**
     * 基础信息入参校验
     *
     * @param companyMemBaseInfo
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private boolean checkSubParm(CompanyMemBaseInfo companyMemBaseInfo, ReturnMsg<String> returnMsg) {
        if (companyMemBaseInfo == null || StringUtils.isBlank(companyMemBaseInfo.getAreaId())
                || StringUtils.isBlank(companyMemBaseInfo.getCityId())
                || StringUtils.isBlank(companyMemBaseInfo.getCompanyName())
                || StringUtils.isBlank(companyMemBaseInfo.getCustMobile())
                || StringUtils.isBlank(companyMemBaseInfo.getCustName())
                || StringUtils.isBlank(companyMemBaseInfo.getEmail())
                || StringUtils.isBlank(companyMemBaseInfo.getOfficeAddress())
                || StringUtils.isBlank(companyMemBaseInfo.getProvinceId())
                || StringUtils.isBlank(companyMemBaseInfo.getChannel())) {
            return false;
        }

        if (!checkString(EMAIL_REGEX, companyMemBaseInfo.getEmail())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "邮箱不合法");
            return false;
        }
        if (companyMemBaseInfo.getEmail().length() > 50) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "邮箱长度超长");
            return false;
        }
        if (!checkString(ADDRESS_REGEX, companyMemBaseInfo.getOfficeAddress())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "办公地址不合法");
            return false;
        }
        if (!checkString(NAME_REGEX, companyMemBaseInfo.getCompanyName())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "公司简称不合法");
            return false;
        }
        if (companyMemBaseInfo.getCompanyName().length() > 60) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "公司简称超长");
            return false;
        }
        if (!checkString(MOBILE_REGEX, companyMemBaseInfo.getCustMobile())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "联系方式不合法");
            return false;
        }
        if (!checkString(NAME_REGEX, companyMemBaseInfo.getCustName())) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "客户姓名不合法");
            return false;
        }

        if (companyMemBaseInfo.getCustName().length() > 32 || companyMemBaseInfo.getCustName().length() < 2) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "客户姓名长度在2到32位之间");
            return false;
        }

        return true;
    }

    private boolean checkString(String reg, String content) {
        if (StringUtils.isBlank(content) || StringUtils.isBlank(reg)) {
            return false;
        }
        // 编译正则表达式
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(content);
        // 字符串是否与正则表达式相匹配
        boolean rs = matcher.matches();
        return rs;
    }

}
